package cn.xiangxiang.service.impl;

import cn.xiangxiang.mapper.goods.SpecMapper;
import cn.xiangxiang.pojo.goods.Spec;
import cn.xiangxiang.pojo.goods.Template;
import cn.xiangxiang.service.goods.SpecService;
import cn.xiangxiang.service.goods.TemplateService;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SpecService.class)
public class SpecServiceImpl extends ServiceImpl<SpecMapper, Spec> implements SpecService {

    @Autowired
    private TemplateService templateService;

    @Override
    public Page<Spec> findConditionPage(Integer startpage, Integer pagesize, Map<String,Object> map) {

        Page<Spec> page = new Page<>(startpage, pagesize);
        Page<Spec> paraPage = page(page, getCondition(map));
        return paraPage;
    }

    @Transactional
    public void saveSpec(Spec spec) {
        save(spec);

        Template template = templateService.getById(spec.getTemplateId());

        template.setSpecNum(template.getSpecNum()+1);

        templateService.updateById(template);

    }

    @Transactional
    public void delById(Integer id) {
        // 先查询
        Spec spec = getById(id);

        removeById(id);

        Template template = templateService.getById(spec.getTemplateId());

        template.setSpecNum(template.getSpecNum()-1);

        templateService.updateById(template);

    }

    @Override
    public List<Spec> findByTemplateId(Integer templateId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("template_id",templateId);
        List<Spec> specList = listByMap(map);
        return specList;
    }

    private QueryWrapper<Spec> getCondition(Map<String,Object> map){
        QueryWrapper<Spec> wrapper = new QueryWrapper<>();
        if(map!=null){
            if(map.get("name")!=null){
                wrapper.like("name",map.get("name"));
            }
            if(map.get("templateId")!=null){
                wrapper.eq("template_id",map.get("templateId"));
            }
        }
        return wrapper;
    }
}
